const express = require('express');
// 创建路由
const router = express.Router();

// bcrypt 加密
const bcrypt = require('bcryptjs');

// mongodb User模型
const User = require('../models/User')

// jsonwebtoken
const jwt = require('jsonwebtoken');

// keys
const keys = require('../config/keys');

// passport
const passport = require('passport');

/**
 * @route POST /api/user/register
 * @desc 用户注册
 * @access public
 */
router.post('/register', (req, res) => {
  // 判断是否存在邮箱
  User.findOne({ email: req.body.email })
    .then(result => {
      if (result) {
        return res.json({ success: false, message: '已存在该邮箱' })
      } else {
        bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(req.body.password, salt, (err, hash) => {
            User.create({
                username: req.body.username,
                email: req.body.email,
                password: hash
              })
              .then(user => res.json({ success: true, message: '注册成功' }))
          });
        });
      }
    })
})

/**
 * @route POST /api/user/login
 * @desc 用户登录
 * @access public
 */
router.post('/login', (req, res) => {
  User.findOne({ email: req.body.email })
    .then(result => {
      if (!result) {
        return res.json({ success: false, message: '找不到该邮箱' })
      } else {
        // 加密判断 参数1:用户登录的密码 参数2:在数据库找到的密码
        bcrypt.compare(req.body.password, result.password, (err, pass) => {
          if (!pass) {
            return res.json({ success: false, message: '密码错误' })
          } else {
            // res.json({ success: true, message: '密码正确' })
            const rule = {
              id: result._id,
              username: result.username,
              email: result.email,
            }
            jwt.sign(rule, keys.secretOrKey, { expiresIn: keys.expiresIn }, function(err, token) {
              res.json({
                success: true,
                message: '登录成功',
                token: 'Bearer ' + token,
              })
            });
          }
        });
      }
    })
})

/**
 * @route POST /api/user/indexjwt
 * @desc index页面token判断
 * @access public
 */
router.get('/indexjwt', passport.authenticate("jwt", { session: false }), (req, res) => {
  res.json();
})

/**
 * @route POST /api/user/jwttest
 * @desc jwt测试
 * @access public
 */
router.get('/jwttest', passport.authenticate("jwt", { session: false }), (req, res) => {
  // passport 返回user  return done(null, user)
  res.json(req.user);
})



module.exports = router;